﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Dapper.Extensions;
using Ymatou.ServiceCenter.Domain.IRepositories;
using Ymatou.ServiceCenter.Domain.Models;
using Ymatou.CommonService;

namespace Ymatou.ServiceCenter.Repository
{
    public class ServiceDependencySamplingRepository : RepositoryBase<ServiceDependencySampling>, IServiceDependencySamplingRepository
    {

        public ServiceDependencySampling GetServiceDependencySampling(string consumerAppId, string providerAppId,
            DateTime beginTime, DateTime endTime)
        {
            if (string.IsNullOrWhiteSpace(consumerAppId))
                throw new ArgumentNullException("consumerAppId");
            if (string.IsNullOrWhiteSpace(providerAppId))
                throw new ArgumentNullException("providerAppId");

            ServiceDependencySampling sampling;

            string sql = @"SELECT sum(TotalRequestElapsedMilliseconds) as TotalRequestElapsedMilliseconds, 
sum(TotalRequestTimes) as TotalRequestTimes,
sum(SamplingElapsedSeconds) as  SamplingElapsedSeconds, 
 sum(TotalRequestTimes) as TotalRequestTimes,
sum(TotalFailTimes) as TotalFailTimes
 from servicedependencysampling where ConsumerAppId=@ConsumerAppId and ProviderAppId=@ProviderAppId and BeginTime>=@BeginTime and EndTime<=@EndTime";
            DynamicParameters dynamicParameters = new DynamicParameters();
            dynamicParameters.Add("ConsumerAppId", consumerAppId);
            dynamicParameters.Add("ProviderAppId", providerAppId);
            dynamicParameters.Add("BeginTime", beginTime);
            dynamicParameters.Add("EndTime", endTime);
            using (IDbContext db = new DbContext())
            {
                sampling = db.Query<ServiceDependencySampling>(sql, dynamicParameters).SingleOrDefault();
            }
            if (sampling == null)
                return null;
            sampling.ConsumerAppId = consumerAppId;
            sampling.ProviderAppId = providerAppId;
            sampling.BeginTime = beginTime;
            sampling.EndTime = endTime;
            return sampling;
        }

        public int TryInsert(IList<ServiceDependencySampling> samplings)
        {
            try
            {
                int affectedRows = 0;

                if (samplings == null || !samplings.Any()) return 0;

                foreach (ServiceDependencySampling sampling in samplings)
                {
                    this.Insert("Default", "servicedependencysampling", sampling);
                    affectedRows++;
                }

                return affectedRows;
            }
            catch (Exception ex)
            {
                ApplicationLog.Error(string.Format("[TryInsertServiceDependencySampling]异常：{0}", ex.Message), ex);
                return -1;
            }
        }
    }
}
